<template>
  <view class="order-closure-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="泊位列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <up-search :clearabled="true" :showAction="false" placeholder="请输入泊位号"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="order-closure-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              泊位号：<text class="number">5168</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag text="待审核" type="warning"></up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  申请时间：
                </text>
                <text class="value">
                  2025-9-2 11:02:35
                </text>
              </view>
              <view class="item">
                <text class="label">
                  确认时间：
                </text>
                <text class="value">
                  2025-9-2 11:02:35
                </text>
              </view>
              <view class="item">
                <text class="label">
                  申请原因：
                </text>
                <text class="value">
                  客户主动关闭
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button type="primary" text="通过申诉" class="custom-style" @click="handlePass(item)"></up-button>
                <up-button type="error" text="拒绝申诉" class="custom-style" @click="handleRefuse(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 通过申诉modal -->
    <up-modal :show="passModalVisible" title="通过申诉" :showCancelButton="true" confirmText="确认通过" 
      @confirm="confirmPass" @cancel="passModalVisible = false">
      <view class="modal-content">
        <view class="user-info">
          <text class="info-text">确定要通过此泊位申诉吗？</text>
        </view>
        <view class="form-item">
          <text class="label">审核备注：</text>
          <up-textarea v-model="passForm.remark" placeholder="请输入审核备注（可选）" :maxlength="200" count
            showWordLimit></up-textarea>
        </view>
      </view>
    </up-modal>

    <!-- 拒绝申诉modal -->
    <up-modal :show="refuseModalVisible" title="拒绝申诉" :showCancelButton="true" confirmText="确认拒绝" 
      @confirm="confirmRefuse" @cancel="refuseModalVisible = false">
      <view class="modal-content">
        <view class="user-info">
          <text class="info-text">确定要拒绝此泊位申诉吗？</text>
        </view>
        <view class="form-item">
          <text class="label">拒绝原因：<text class="required">*</text></text>
          <up-textarea v-model="refuseForm.remark" placeholder="请输入拒绝原因" :maxlength="200" count
            showWordLimit></up-textarea>
        </view>
      </view>
    </up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getBerthUpdateLogList, authorBerthUpdateLog } from '@/api';

// 搜索关键词
const keyword = ref('');

// 筛选条件
const statusIndex = ref(0); // 审核状态索引
const ownIndex = ref(0); // 是否本人索引

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待审核' },
  { name: '已审核' },
];
const currentTab = ref(0);

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 删除不需要的添加功能

// Modal相关变量
const passModalVisible = ref(false);
const refuseModalVisible = ref(false);
const currentItem = ref<any>(null);
const passForm = ref({
  remark: ''
});
const refuseForm = ref({
  remark: ''
});

// 打开通过申诉modal
const handlePass = (item: any) => {
  currentItem.value = item;
  passForm.value.remark = '';
  passModalVisible.value = true;
}

// 确认通过申诉
const confirmPass = () => {
  // 通过申诉不需要必填备注
  
  // 调用审核通过接口
  uni.showLoading({ title: '处理中...' });
  
  authorBerthUpdateLog({
    bizCode: currentItem.value.bizCode, // 审核ID
    author: 0, // 0表示审核通过
    dealRemark: passForm.value.remark // 审核备注
  }).then(res => {
    uni.hideLoading();
    if (res.success) {
      uni.showToast({
        title: '审核已通过',
        icon: 'success'
      });
      
      // 关闭modal
      passModalVisible.value = false;
      
      // 刷新列表
      if (paging.value) {
        paging.value.reload();
      }
    } else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
    console.error('审核失败', err);
  });
}

// 打开拒绝申诉modal
const handleRefuse = (item: any) => {
  currentItem.value = item;
  refuseForm.value.remark = '';
  refuseModalVisible.value = true;
}

// 确认拒绝申诉
const confirmRefuse = () => {
  if (!refuseForm.value.remark.trim()) {
    uni.showToast({
      title: '请输入拒绝原因',
      icon: 'none'
    });
    return;
  }
  
  // 调用审核拒绝接口
  uni.showLoading({ title: '处理中...' });
  
  authorBerthUpdateLog({
    bizCode: currentItem.value.bizCode, // 审核ID
    author: 1, // 1表示拒绝审核
    dealRemark: refuseForm.value.remark // 拒绝原因
  }).then(res => {
    uni.hideLoading();
    if (res.success) {
      uni.showToast({
        title: '已拒绝申诉',
        icon: 'success'
      });
      
      // 关闭modal
      refuseModalVisible.value = false;
      
      // 刷新列表
      if (paging.value) {
        paging.value.reload();
      }
    } else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
    console.error('审核失败', err);
  });
}

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}


// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 根据tab索引映射状态值：0-全部(-1), 1-待审核(0), 2-已审核(1)
    let status = -1; // 默认全部
    if (currentTab.value === 1) {
      status = 0; // 待审核
    } else if (currentTab.value === 2) {
      status = 1; // 已审核
    }
    
    const result: any = await getBerthUpdateLogList({ 
      ...params, 
      isAuthor: status,
      isOwn: ownIndex.value === 0 ? "" : (ownIndex.value === 2 ? "1" : "0"),
      keyword: keyword.value || ""
    })
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}


// 搜索按钮点击事件
const handleSearch = () => {
};

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页逻辑
  console.log('查看详情:', row);
};

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.order-closure-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  &-item {
    display: flex;
    flex: 1;
    align-items: center;
    text-align: center;

    .item-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}

.custom-style {
  margin-left: 10rpx;
}

/* Modal样式 */
.modal-content {
  padding: 10px;
}

.user-info {
  margin-bottom: 15px;
}

.info-text {
  font-size: 14px;
  color: #333;
}

.form-item {
  margin-bottom: 10px;
}

.form-item .label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}

.form-item .required {
  color: #f56c6c;
}
</style>